/**
 * @filename:SaleOrderServiceImpl Feb 18, 2025
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2022 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.service.impl;

import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.SaleOrderDao;
import com.wonder.app.mapper.SaleOrderDetailDao;
import com.wonder.app.service.*;
import com.wonder.app.request.SaleOrderRequest;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.common.AjaxResult;

import java.util.*;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.wonder.utils.DateUtils;

/**   
 * @Description:TODO(销售订单服务实现)
 *
 * @version: 1.1.0
 * @author: Wonder
 * 
 */
@Service
public class SaleOrderServiceImpl  extends ServiceImpl<SaleOrderDao, SaleOrder> implements SaleOrderService  {

	private static final Logger _logger = LoggerFactory.getLogger(PurReturnServiceImpl.class);
	@Autowired
	private SaleOrderService saleOrderService;
	@Autowired
	private SaleOrderDao saleOrderDao;

	@Autowired
	private SyncOrderService syncOrderService;
	@Autowired
	private SaleOrderDetailDao saleOrderDetailDao;
	@Autowired
	private SaleOrderDetailService saleOrderDetailService;
	@Autowired
	private IVtuzxKingdeeService vtuzxKingdeeService;
	@Autowired
	private SyncKingdeeOrderService syncKingdeeOrderService;



	@Autowired
	private MaterialService materialService;

    /**
     * 验证销售订单信息
     *
     * @param saleOrder
     * @param type
     * @return String
     */
    @Override
    public String validate(SaleOrder saleOrder,String type){


       return "";
    }


    /**
	 * Description:销售订单分页返回
	 * @param request //检索条件
	 * @param page //分页参数
	 * @return IPage<SaleOrder>   //分页记录
	 */
	@Override
	public IPage<SaleOrder> selectList(SaleOrderRequest request, Page<SaleOrder> page){
	    LambdaQueryWrapper<SaleOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();

	    if (null != request.getId()) {
	       lambdaQueryWrapper.eq(SaleOrder::getId, request.getId());
	      }

        if (StringUtils.hasText(request.getCusTomer())) {
			    lambdaQueryWrapper.like(SaleOrder::getCusTomer, request.getCusTomer());
		    }

		if (StringUtils.hasText(request.getSyncNo())) {
			lambdaQueryWrapper.like(SaleOrder::getSyncNo, request.getSyncNo());
		}


		if (StringUtils.hasText(request.getCusBillNo())) {
			    lambdaQueryWrapper.like(SaleOrder::getCusBillNo, request.getCusBillNo());
		    }

        if (request.getInDate() != null){
        	Date[] inDate=request.getInDate();
        	if(inDate.length>0)
        	  lambdaQueryWrapper.ge(SaleOrder::getInDate, inDate[0]);
        	if(inDate.length==2)
        	  lambdaQueryWrapper.le(SaleOrder::getInDate,inDate[1]);

        }

		if (request.getInDate() != null) {
			Date[] fCREATEDATE = request.getInDate();
			if (fCREATEDATE.length > 0) {
				// 设置开始时间为当天的零点
				Calendar startCalendar = Calendar.getInstance();
				startCalendar.setTime(fCREATEDATE[0]);
				startCalendar.set(Calendar.HOUR_OF_DAY, 0);
				startCalendar.set(Calendar.MINUTE, 0);
				startCalendar.set(Calendar.SECOND, 0);
				startCalendar.set(Calendar.MILLISECOND, 0);
				Date startDate = startCalendar.getTime();
				lambdaQueryWrapper.ge(SaleOrder::getInDate, startDate);
			}
			if (fCREATEDATE.length == 2) {
				// 设置结束时间为当天的24点
				Calendar endCalendar = Calendar.getInstance();
				endCalendar.setTime(fCREATEDATE[1]);
				endCalendar.set(Calendar.HOUR_OF_DAY, 23);
				endCalendar.set(Calendar.MINUTE, 59);
				endCalendar.set(Calendar.SECOND, 59);
				endCalendar.set(Calendar.MILLISECOND, 999);
				Date endDate = endCalendar.getTime();
				lambdaQueryWrapper.le(SaleOrder::getInDate, endDate);
			}
		}


        if (StringUtils.hasText(request.getUser())) {
			    lambdaQueryWrapper.like(SaleOrder::getUser, request.getUser());
		    }


		lambdaQueryWrapper.orderByDesc(SaleOrder::getId);
		Page<SaleOrder> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
		return selectPage;
    }

	/**
	 * 导入
	 */
	@Override
	public AjaxResult<Object> importData(String userName,Long user_id,List<Map<String,Object>> map) throws Exception{
		if(map==null || map.size()==0) return AjaxResult.failed(MessageUtils.message("没有获取到数据，请检查模板sheet页"));
		Map<String,Object> orderMap = new HashMap<>();//key:客户订单号val:单据头
		Map<String,Object> detailMap = new HashMap<>();//key:客户订单号 val:单据体集合
		List<String> cusBillList = new ArrayList<>();//客户订单号集合
		//模板校验
		String headCusBillNo = map.get(0).get("__EMPTY").toString();//客户订单号
		String headTyNo = VtuzxUtil.getString(map.get(0),"销售订单");//TY件号
		String headCustomer = VtuzxUtil.getString(map.get(0),"__EMPTY_3");//客户

		if (!"客户订单号".equals(headCusBillNo) || !"TY件号".equals(headTyNo) || !"客户".equals(headCustomer) ){
			throw new RuntimeException("模板有误，请检查模板");
		}

		//前期校验excel模板数据
		Boolean aBoolean = checkSaleOrder(userName, user_id, map);
		if (!aBoolean){
			throw new RuntimeException("模板数据校验未通过,请查看传单日志查看具体信息");
		}
		List<String> customerNameList = new ArrayList<>();//客户名称集合
		List<String> currencyList = new ArrayList<>();//币别名称集合
		List<String> tyNoList = new ArrayList<>();//ty件号集合
		//订单同步开始
		String tbbillNo = syncOrderService.startSyncOrder(userName,user_id,"销售订单");
		for (Map<String,Object>  item:map){
			String cusBillNo = item.get("__EMPTY").toString();//客户订单号
			if ("客户订单号".equals(cusBillNo)){
				continue;
			}
			if(!cusBillList.contains(cusBillNo)){
				cusBillList.add(cusBillNo);
			}

			Integer times = VtuzxUtil.getInt(item,"__EMPTY_1");//下单日期(时间戳)
			Integer week = VtuzxUtil.getInt(item,"__EMPTY_2");//下单周数
			String customer = VtuzxUtil.getString(item,"__EMPTY_3");//客户
			if(!customerNameList.contains(customer)){
				customerNameList.add(customer);
			}

			String cusPartNo = VtuzxUtil.getString(item,"__EMPTY_4");//客户件号
			String tyNo = VtuzxUtil.getString(item,"销售订单");//TY件号
			if(!tyNoList.contains(tyNo)){
				tyNoList.add(tyNo);
			}

			Double count = VtuzxUtil.getDouble(item,"__EMPTY_5");//数量
			double taxPrice = VtuzxUtil.getDouble(item,"__EMPTY_6");//含税单价
			Long taxRate = VtuzxUtil.getLong(item,"__EMPTY_7");//税率
			double totalPrice = VtuzxUtil.getDouble(item,"__EMPTY_8");//价税合计
			Integer shipTime = VtuzxUtil.getInt(item,"__EMPTY_9");//船期
			Integer shipWeek = VtuzxUtil.getInt(item,"__EMPTY_10");//船期周数
			Integer deliveTimes = VtuzxUtil.getInt(item,"__EMPTY_11");//计划出货日期
			Integer deliveWeek = VtuzxUtil.getInt(item,"__EMPTY_12");//计划出货日期周数
			String currency = VtuzxUtil.getString(item,"__EMPTY_14");//币别
			String FCustId = VtuzxUtil.getString(item,"__EMPTY_15");//客户
			if (!currencyList.contains(currency)){
				currencyList.add(currency);
			}
			if(!customerNameList.contains(FCustId)){
				customerNameList.add(FCustId);
			}

			SaleOrder saleOrder = VtuzxUtil.getObject(orderMap,cusBillNo);
			if (null == saleOrder){
				SaleOrder order = new SaleOrder();
				order.setCusBillNo(cusBillNo);
				order.setCusTomer(customer);
				order.setInDate(conVerDate(times));
				order.setWeekNo(week.toString());
				order.setSyncNo(tbbillNo);//同步单号
				order.setFCustId(FCustId);//结算客户
				orderMap.put(cusBillNo,order);
			}
			//map中添加详情数据
			List<SaleOrderDetail> orderDetailList = VtuzxUtil.getObject(detailMap,cusBillNo);
			if (null == orderDetailList || orderDetailList.size() == 0){
				List<SaleOrderDetail> orderDetails = new ArrayList<>();
				SaleOrderDetail detail = new SaleOrderDetail();
				detail.setCusBillNo(cusBillNo);
				detail.setCusPartNo(cusPartNo);
				detail.setTyPartNo(tyNo);
				detail.setTaxPrice(taxPrice);
				detail.setTaxRate(taxRate);
				detail.setTotalPrice(totalPrice);
				detail.setQty(count);
				detail.setShipDate(conVerDate(shipTime));
				detail.setShipWeek(shipWeek.toString());
				detail.setDeliveDate(conVerDate(deliveTimes));
				detail.setDeliveWeek(deliveWeek.toString());
				detail.setCurrency(currency);
				orderDetails.add(detail);
				detailMap.put(cusBillNo,orderDetails);
			} else {
				SaleOrderDetail detail = new SaleOrderDetail();
				detail.setCusPartNo(cusPartNo);
				detail.setCusBillNo(cusBillNo);
				detail.setTyPartNo(tyNo);
				detail.setTaxPrice(taxPrice);
				detail.setTaxRate(taxRate);
				detail.setTotalPrice(totalPrice);
				detail.setQty(count);
				detail.setShipDate(conVerDate(shipTime));
				detail.setShipWeek(shipWeek.toString());
				detail.setDeliveDate(conVerDate(deliveTimes));
				detail.setDeliveWeek(deliveWeek.toString());
				detail.setCurrency(currency);
				orderDetailList.add(detail);
				detailMap.put(cusBillNo,orderDetailList);
			}

		}
		List<SyncOrderDetail> orderDetailList = new ArrayList<>();//需要保存到传单日志详情表中的数据

		//查询出物料，币别，客户所需的金蝶编码等信息
		List<Map<String, Object>> materialByNo = materialService.getMaterialByNo(tyNoList);
		//将查询到的物料信息转成map
		Map<String, Object> materialToMap = changeMaterialToMap(materialByNo);
		Map<String, Object> customerMap = materialService.getCustomerName(customerNameList);
		Map<String, Object> currencyMap = materialService.getCurrencyNo(currencyList);
		//查询出已经保存过的销售订单
		List<String> saveOrderNoList =  selectSaleOrderNo(cusBillList);
		//数据库批量保存数据
		boolean saveBatch = saveBatchSaleOrder(orderMap,detailMap,cusBillList,saveOrderNoList);
		for (String cusBillNo: cusBillList){
			SyncOrderDetail syncOrderDetail = new SyncOrderDetail();
			syncOrderDetail = new SyncOrderDetail();
			syncOrderDetail.setOrderNo(cusBillNo);//客户订单号
			syncOrderDetail.setBillNo(tbbillNo);
			syncOrderDetail.setCreateTime(new Date());
			syncOrderDetail.setUpdateTime(new Date());

			//检验当前客户订单号是否上传过
//			Boolean checkresult = checkSaleOrder(cusBillNo);
			Boolean checkresult = saveOrderNoList.contains(cusBillNo);
			if (checkresult){
				syncOrderDetail.setMessage(String.format("单据编号:%s,已经导入过,不允许重复导入",cusBillNo));
				syncOrderDetail.setIsSuccess(false);
				orderDetailList.add(syncOrderDetail);
				continue;
			}


			SaleOrder saleOrder = VtuzxUtil.getObject(orderMap,cusBillNo);
			List<SaleOrderDetail> saleOrderDetailList = VtuzxUtil.getObject(detailMap,cusBillNo);
			//数据库保存数据
//			boolean saveBatch = saveSaleOrder(saleOrder, saleOrderDetailList);
			try {
				syncKingdeeOrderService.syncSaleOrder(saleOrder, saleOrderDetailList,materialToMap,customerMap,currencyMap,user_id);
				syncOrderDetail.setIsSuccess(true);
			} catch (Exception e){
				//捕获异常删除已经保存的数据
				deleteSaleOrder(saleOrder,saleOrderDetailList);
				syncOrderDetail.setIsSuccess(false);
				syncOrderDetail.setMessage(e.getMessage());
			}
			orderDetailList.add(syncOrderDetail);
		}
		Map<String, Object> data = syncOrderService.endSyncOrder(orderDetailList,tbbillNo);
		return AjaxResult.success(data);

	}


	/**
	 * 查询已经保存过的生产订单
	 * @param cusBillList
	 * @return
	 */
	private List<String> selectSaleOrderNo(List<String> cusBillList) {
		LambdaQueryWrapper<SaleOrder> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(SaleOrder::getCusBillNo,cusBillList);
		List<SaleOrder> saleOrderList = saleOrderDao.selectList(queryWrapper);
		List<String>  saveOrderNoList = new ArrayList<>();
		if (!VtuzxUtil.isEmpty(saleOrderList)){
			for (SaleOrder  saleOrder : saleOrderList){
				String billNo = saleOrder.getCusBillNo();
				if (!saveOrderNoList.contains(billNo)){
					saveOrderNoList.add(billNo);
				}
			}
		}

		return saveOrderNoList;
	}


	/**
	 * 批量保存销售订单(mysql)
	 * @param orderMap
	 * @param detailMap
	 * @return
	 */
	private boolean saveBatchSaleOrder(Map<String, Object> orderMap, Map<String, Object> detailMap,List<String> cusBillNoList,List<String> saveOrderNoList) {
		List<SaleOrder> saleOrderList = new ArrayList<>();
		List<SaleOrderDetail> detailList = new ArrayList<>();
		for (String cusBillNo : cusBillNoList){
			if(saveOrderNoList.contains(cusBillNo)){
				continue;
			}
			SaleOrder saleOrder = VtuzxUtil.getObject(orderMap,cusBillNo);
			List<SaleOrderDetail> saleOrderDetailList = VtuzxUtil.getObject(detailMap,cusBillNo);
			saleOrderList.add(saleOrder);
			detailList.addAll(saleOrderDetailList);
		}
		boolean b = saleOrderService.saveOrUpdateBatch(saleOrderList);
		boolean r = saleOrderDetailService.saveOrUpdateBatch(detailList);
		return b && r;

	}


	/**
	 * 校验销售订单导入的数据
	 * @param user_id
	 * @param map
	 * @return
	 * @throws Exception
	 */
	private Boolean checkSaleOrder(String userName,Long user_id,List<Map<String,Object>> map) throws Exception{
		//添加行号
		int i = 3;
		for (Map<String,Object> data : map){
			data.put("line",i);
			i++;
		}
		//添加之前做一个删除
		materialService.deleteSaleOrder(userName,user_id);
		//sqlserver数据库添加当前导入的数据
		materialService.saveSaleOrder(userName,user_id,map);
		//校验客户订单号
		List<Map<String,Object>> checkCusBill =  materialService.checkCusBillNo(user_id);
		//校验物料
		List<Map<String,Object>> checkMaterial =  materialService.checkMaterial(user_id);
		//校验客户
		List<Map<String,Object>> checkCustomer =  materialService.checkCustomer(user_id);
		//校验数量是否都大于0
		List<Map<String,Object>> checkCount =  materialService.checkCount(user_id);

		//校验船期
		List<Map<String,Object>> checkSheep =  materialService.checkSheep(user_id);
		//判断查询的数据如果都为空的话说明模板数据校验通过可以导入,如果不为空的话添加日志信息并且停止传单
		if (VtuzxUtil.isEmpty(checkCusBill) &&  VtuzxUtil.isEmpty(checkMaterial) && VtuzxUtil.isEmpty(checkCustomer)
				&& VtuzxUtil.isEmpty(checkCount) && VtuzxUtil.isEmpty(checkSheep)){
			return true;
		}  else {//有一个不等于空的就说明有问题,需要向日志中添加信息
			saveOrderLog(userName,user_id,checkCusBill,checkMaterial,checkCustomer,checkCount,checkSheep);
			return false;
		}

	}

	/**
	 * 模板级校验添加日志信息
	 * @param checkCusBill
	 * @param checkMaterial
	 * @param checkCustomer
	 * @param checkCount
	 */
	private void saveOrderLog(String userName,Long user_id,List<Map<String,Object>> checkCusBill,List<Map<String,Object>> checkMaterial,
							  List<Map<String,Object>> checkCustomer,List<Map<String,Object>> checkCount,List<Map<String,Object>> checkSheep){
		String tbbillNo = syncOrderService.startSyncOrder(userName,user_id,"销售订单模板数据校验");
		List<SyncOrderDetail> orderDetailList = new ArrayList<>();
		if (!VtuzxUtil.isEmpty(checkCusBill)){//客户订单号校验
			for (Map<String,Object> data : checkCusBill){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				SyncOrderDetail syncOrderDetail = new SyncOrderDetail();
				syncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				syncOrderDetail.setBillNo(tbbillNo);
				syncOrderDetail.setCreateTime(new Date());
				syncOrderDetail.setUpdateTime(new Date());
				syncOrderDetail.setIsSuccess(false);
				syncOrderDetail.setMessage("第" + line + "行的客户订单号不允许为空");
				orderDetailList.add(syncOrderDetail);
			}
		}

		if (!VtuzxUtil.isEmpty(checkMaterial)){//物料校验
			for (Map<String,Object> data : checkMaterial){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				SyncOrderDetail syncOrderDetail = new SyncOrderDetail();
				syncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				syncOrderDetail.setBillNo(tbbillNo);
				syncOrderDetail.setCreateTime(new Date());
				syncOrderDetail.setUpdateTime(new Date());
				syncOrderDetail.setIsSuccess(false);
				syncOrderDetail.setMessage("第" + line + "行的TY件号未审核,或者不存在,或者已禁用,请确认");
				orderDetailList.add(syncOrderDetail);
			}
		}

		if (!VtuzxUtil.isEmpty(checkCustomer)){//客户校验
			for (Map<String,Object> data : checkCustomer){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				SyncOrderDetail syncOrderDetail = new SyncOrderDetail();
				syncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				syncOrderDetail.setBillNo(tbbillNo);
				syncOrderDetail.setCreateTime(new Date());
				syncOrderDetail.setUpdateTime(new Date());
				syncOrderDetail.setIsSuccess(false);
				syncOrderDetail.setMessage("第" + line + "行的客户未审核,或者不存在,或者已禁用,请确认");
				orderDetailList.add(syncOrderDetail);
			}
		}

		if (!VtuzxUtil.isEmpty(checkCount)){//数量校验
			for (Map<String,Object> data : checkCount){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				SyncOrderDetail syncOrderDetail = new SyncOrderDetail();
				syncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				syncOrderDetail.setBillNo(tbbillNo);
				syncOrderDetail.setCreateTime(new Date());
				syncOrderDetail.setUpdateTime(new Date());
				syncOrderDetail.setIsSuccess(false);
				syncOrderDetail.setMessage("第" + line + "的数量必须大于0");
				orderDetailList.add(syncOrderDetail);
			}
		}

		if (!VtuzxUtil.isEmpty(checkSheep)){//数量校验
			for (Map<String,Object> data : checkSheep){
				int line = VtuzxUtil.getInt(data,"LINE");//行号
				SyncOrderDetail syncOrderDetail = new SyncOrderDetail();
				syncOrderDetail.setOrderNo("销售订单模板数据校验");//客户订单号
				syncOrderDetail.setBillNo(tbbillNo);
				syncOrderDetail.setCreateTime(new Date());
				syncOrderDetail.setUpdateTime(new Date());
				syncOrderDetail.setIsSuccess(false);
				syncOrderDetail.setMessage("第" + line + "行船期不能为空,不能小于单据日期,或者单据日期不能为空,请确认");
				orderDetailList.add(syncOrderDetail);
			}
		}

		syncOrderService.endSyncOrder(orderDetailList,tbbillNo);
	}

	/**
	 * 保存销售订单的信息
	 * @param
	 * @param
	 * @return
	 */
	private Boolean saveSaleOrder(SaleOrder saleOrder,List<SaleOrderDetail> detailList){
//		List<SaleOrder> saleOrderList = new ArrayList<>();
//		List<SaleOrderDetail> saleOrderDetailList = new ArrayList<>();
//		for (Map.Entry entry : orderMap.entrySet()){
//			SaleOrder saleOrder = (SaleOrder) entry.getValue();
//			saleOrderList.add(saleOrder);
//		}
//		for (Map.Entry entry : detailMap.entrySet()){
//			List<SaleOrderDetail> detailList = (List<SaleOrderDetail>) entry.getValue();
//			saleOrderDetailList.addAll(detailList);
//		}
		boolean saveBatch = saleOrderService.saveOrUpdate(saleOrder);
		boolean detailBatch = saleOrderDetailService.saveOrUpdateBatch(detailList);
		return saveBatch && detailBatch;
	}

	private void deleteSaleOrder (SaleOrder saleOrder,List<SaleOrderDetail> detailList){
		List<Long> detailIdList = new ArrayList<>();
		for (SaleOrderDetail detail : detailList){
			Long id = detail.getId();
			if (!detailIdList.contains(id)){
				detailIdList.add(id);
			}
		}
		saleOrderService.removeById(saleOrder.getId());
		saleOrderDetailService.removeBatchByIds(detailIdList);
	}
	/**
	 * Excel日期转换
	 * @param times
	 * @return
	 */
	public Date conVerDate(int times){
		Calendar calendar = Calendar.getInstance();
		calendar.set(1900,Calendar.JANUARY,1);
		calendar.add(Calendar.DAY_OF_MONTH,times -2);
		Date date = calendar.getTime();
		return date;
	}

	/**
	 * 检查是否导入过该订单
	 * @param BillNo
	 * @return
	 */
	public Boolean checkSaleOrder(String BillNo){
		QueryWrapper<SaleOrder> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("CusBillNo",BillNo);
		SaleOrder saleOrder = saleOrderDao.selectOne(queryWrapper);
		if(saleOrder != null){
			return true;
		}else {
			return false;
		}
	}


	/**
	 * receive详情
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getSaleOrderDetail(Map<String, Object> map) {
		String billNo = map.get("billNo").toString();
		SaleOrder saleorderform = saleOrderDao.selectOne(new LambdaQueryWrapper<SaleOrder>()
				.eq(SaleOrder::getCusBillNo,billNo));
		List<SaleOrderDetail> saleorderList = saleOrderDetailDao.selectList(new LambdaQueryWrapper<SaleOrderDetail>()
				.eq(SaleOrderDetail::getCusBillNo,billNo));
		Map<String,Object> data = new HashMap<>();
		data.put("data",saleorderform);
		data.put("dataList",saleorderList);
		return data;
	}
	/**
	 * 销售出库明细详情
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getSaleOrderDelete(Map<String, Object> map,Long user_id)throws Exception {
		String cusBillNo = map.get("cusBillNo").toString();
		String cuFbillno = "";
		VtuzxKingdeeCloudClient client = null;
		try {
			client = vtuzxKingdeeService.loginKingdeeByUser(user_id);
		} catch (Exception e){
			throw new RuntimeException("金蝶账号密码错误,请维护");
		}
		//根据客户订单号查询金蝶销售订单
		List<VtuzxMap> prdcumQuery = vtuzxKingdeeService.query(client,"SAL_SaleOrder", new VtuzxArrayList<>(
						"F_PSUH_Text_qtr",
						"FBillNo"
				),
				// 组合两个过滤条件（规格型号 + 物料分组）
				String.format("F_PSUH_Text_qtr = '%s' ",
						cusBillNo), null, 0, 0);

		if (!VtuzxUtil.isEmpty(prdcumQuery)) {
			cuFbillno = VtuzxUtil.getString(prdcumQuery.get(0),"FBillNo");
			throw new RuntimeException(String.format("该订单已存在不能删除订单号%s 销售订单号%s ", cusBillNo,cuFbillno));
		}
		// 删除本地数据库记录
		int deletedDetails = saleOrderDetailDao.delete(
				new LambdaQueryWrapper<SaleOrderDetail>()
						.eq(SaleOrderDetail::getCusBillNo, cusBillNo)
		);

		int deletedMain = saleOrderDao.delete(
				new LambdaQueryWrapper<SaleOrder>()
						.eq(SaleOrder::getCusBillNo, cusBillNo)
		);

		Map<String, Object> data = new HashMap<>();
		data.put("success", true);
		data.put("message", String.format("主表删除 %d 条，明细表删除 %d 条", deletedMain, deletedDetails));
		return data;
	}

	@Override
	public AjaxResult<Object> importUpdateData(List<Map<String, Object>> map) throws Exception {
		if(map==null || map.size()==0) return AjaxResult.failed(MessageUtils.message("import.file.no.data"));
		Map<String,Object> orderMap = new HashMap<>();//key:客户订单号val:单据头
		Map<String,Object> detailMap = new HashMap<>();//key:客户订单号 val:单据体集合
		List<String> cusBillList = new ArrayList<>();//客户订单号集合
		String headCusBillNo = map.get(0).get("__EMPTY").toString();//客户订单号
		String headTyNo = VtuzxUtil.getString(map.get(0),"销售订单");//TY件号
		String headCustomer = VtuzxUtil.getString(map.get(0),"__EMPTY_3");//客户

		if (!"客户订单号".equals(headCusBillNo) || !"TY件号".equals(headTyNo) || !"客户".equals(headCustomer) ){
			throw new RuntimeException("模板有误，请检查模板");
		}

		for (Map<String,Object>  item:map){
			String cusBillNo = item.get("__EMPTY").toString();//客户订单号
			if ("客户订单号".equals(cusBillNo)){
				continue;
			}

			if(!cusBillList.contains(cusBillNo)){
				cusBillList.add(cusBillNo);
			}

			Integer times = VtuzxUtil.getInt(item,"__EMPTY_1");//下单日期(时间戳)
			Integer week = VtuzxUtil.getInt(item,"__EMPTY_2");//下单周数
			String customer = VtuzxUtil.getString(item,"__EMPTY_3");//客户
			String cusPartNo = VtuzxUtil.getString(item,"__EMPTY_4");//客户件号
			String tyNo = VtuzxUtil.getString(item,"销售订单");//TY件号
			Double count = VtuzxUtil.getDouble(item,"__EMPTY_5");//数量
			double taxPrice = VtuzxUtil.getDouble(item,"__EMPTY_6");//含税单价
			Long taxRate = VtuzxUtil.getLong(item,"__EMPTY_7");//税率
			double totalPrice = VtuzxUtil.getDouble(item,"__EMPTY_8");//价税合计
			Integer shipTime = VtuzxUtil.getInt(item,"__EMPTY_9");//船期
			Integer shipWeek = VtuzxUtil.getInt(item,"__EMPTY_10");//船期周数
			Integer deliveTimes = VtuzxUtil.getInt(item,"__EMPTY_11");//计划出货日期
			Integer deliveWeek = VtuzxUtil.getInt(item,"__EMPTY_12");//计划出货日期周数
			String type = VtuzxUtil.getString(item,"__EMPTY_13");//类型
			String currency = VtuzxUtil.getString(item,"__EMPTY_14");//币别
			//检验当前客户订单号是否上传过
			Boolean checkresult = checkSaleOrder(cusBillNo);
			if (!checkresult){//没有上传
				throw new RuntimeException(String.format("客户订单号:%s,没有导入,无法变更",cusBillNo));
			} else {
				SaleOrder saleOrder = VtuzxUtil.getObject(orderMap,cusBillNo);
				if (null == saleOrder){
					SaleOrder order = saleOrderDao.selectOne(new LambdaQueryWrapper<SaleOrder>()
							.eq(SaleOrder::getCusBillNo, cusBillNo));
					order.setCusBillNo(cusBillNo);
					order.setCusTomer(customer);
					order.setInDate(conVerDate(times));
					order.setWeekNo(week.toString());
					orderMap.put(cusBillNo,order);
				}
				//map中添加详情数据
				List<SaleOrderDetail> orderDetailList = VtuzxUtil.getObject(detailMap,cusBillNo);
				if (null == orderDetailList || orderDetailList.size() == 0){//第一次向map中添加数据
					List<SaleOrderDetail> orderDetails = new ArrayList<>();
					//判断变更类型是新增，修改，删除新增的话数据库没有值
					if ("新增".equals(type)){//新增的话校验数据库不允许有当亲ty件号的明细
						SaleOrderDetail saveDetail = saleOrderDetailDao.selectOne(new LambdaQueryWrapper<SaleOrderDetail>()
								.eq(SaleOrderDetail::getCusBillNo, cusBillNo)
								.eq(SaleOrderDetail::getTyPartNo, tyNo));
						if (null != saveDetail){
							throw new RuntimeException(String.format("客户订单号:%s,已经存在TY件号为%s,无法做新增",cusBillNo,tyNo));
						}
						SaleOrderDetail detail = new SaleOrderDetail();
						detail.setCusBillNo(cusBillNo);
						detail.setCusPartNo(cusPartNo);
						detail.setTyPartNo(tyNo);
						detail.setTaxPrice(taxPrice);
						detail.setTaxRate(taxRate);
						detail.setTotalPrice(totalPrice);
						detail.setQty(count);
						detail.setShipDate(conVerDate(shipTime));
						detail.setShipWeek(shipWeek.toString());
						detail.setDeliveDate(conVerDate(deliveTimes));
						detail.setDeliveWeek(deliveWeek.toString());
						detail.setType(type);
						detail.setCurrency(currency);
						orderDetails.add(detail);
						detailMap.put(cusBillNo,orderDetails);
					} else {
						SaleOrderDetail detail = saleOrderDetailDao.selectOne(new LambdaQueryWrapper<SaleOrderDetail>()
								.eq(SaleOrderDetail::getCusBillNo, cusBillNo)
								.eq(SaleOrderDetail::getTyPartNo, tyNo));
						if (null == detail){
							throw new RuntimeException(String.format("客户订单号:%s,不存在TY件号为%s,无法做修改或删除",cusBillNo,tyNo));
						}
						detail.setCusBillNo(cusBillNo);
						detail.setCusPartNo(cusPartNo);
						detail.setTyPartNo(tyNo);
						detail.setTaxPrice(taxPrice);
						detail.setTaxRate(taxRate);
						detail.setTotalPrice(totalPrice);
						detail.setQty(count);
						detail.setShipDate(conVerDate(shipTime));
						detail.setShipWeek(shipWeek.toString());
						detail.setDeliveDate(conVerDate(deliveTimes));
						detail.setDeliveWeek(deliveWeek.toString());
						detail.setType(type);
						detail.setCurrency(currency);
						orderDetails.add(detail);
						detailMap.put(cusBillNo,orderDetails);
					}

				} else {
					if ("新增".equals(type)){
						SaleOrderDetail saveDetail = saleOrderDetailDao.selectOne(new LambdaQueryWrapper<SaleOrderDetail>()
								.eq(SaleOrderDetail::getCusBillNo, cusBillNo)
								.eq(SaleOrderDetail::getTyPartNo, tyNo));
						if (null != saveDetail){
							throw new RuntimeException(String.format("客户订单号:%s,已经存在TY件号为%s,无法做新增",cusBillNo,tyNo));
						}
						SaleOrderDetail detail = new SaleOrderDetail();
						detail.setCusPartNo(cusPartNo);
						detail.setCusBillNo(cusBillNo);
						detail.setTyPartNo(tyNo);
						detail.setTaxPrice(taxPrice);
						detail.setTaxRate(taxRate);
						detail.setTotalPrice(totalPrice);
						detail.setQty(count);
						detail.setShipDate(conVerDate(shipTime));
						detail.setShipWeek(shipWeek.toString());
						detail.setDeliveDate(conVerDate(deliveTimes));
						detail.setDeliveWeek(deliveWeek.toString());
						detail.setType(type);
						detail.setCurrency(currency);
						orderDetailList.add(detail);
						detailMap.put(cusBillNo,orderDetailList);
					} else {
						SaleOrderDetail detail = saleOrderDetailDao.selectOne(new LambdaQueryWrapper<SaleOrderDetail>()
								.eq(SaleOrderDetail::getCusBillNo, cusBillNo)
								.eq(SaleOrderDetail::getTyPartNo, tyNo));
						if (null == detail){
							throw new RuntimeException(String.format("客户订单号:%s,不存在TY件号为%s,无法做修改或删除",cusBillNo,tyNo));
						}
						detail.setCusPartNo(cusPartNo);
						detail.setCusBillNo(cusBillNo);
						detail.setTyPartNo(tyNo);
						detail.setTaxPrice(taxPrice);
						detail.setTaxRate(taxRate);
						detail.setTotalPrice(totalPrice);
						detail.setQty(count);
						detail.setShipDate(conVerDate(shipTime));
						detail.setShipWeek(shipWeek.toString());
						detail.setDeliveDate(conVerDate(deliveTimes));
						detail.setDeliveWeek(deliveWeek.toString());
						detail.setType(type);
						detail.setCurrency(currency);
						orderDetailList.add(detail);
						detailMap.put(cusBillNo,orderDetailList);
					}

				}
			}


		}


		for (String cusBillNo: cusBillList){
			SaleOrder saleOrder = VtuzxUtil.getObject(orderMap,cusBillNo);
			List<SaleOrderDetail> saleOrderDetailList = VtuzxUtil.getObject(detailMap,cusBillNo);
			//数据库保存数据
			boolean saveBatch = saveSaleOrder(saleOrder, saleOrderDetailList);
			try {
				//传销售订单变更单
				syncKingdeeOrderService.syncSaleUpdateOrder(saleOrder, saleOrderDetailList);
			} catch (Exception e){
				//捕获异常删除已经保存的数据
//				deleteSaleOrder(saleOrder,saleOrderDetailList);
				throw new RuntimeException(e.getMessage());
			}
		}
		return AjaxResult.success();

	}

	@Override
	public Map<String, Object> getStok(String stock) throws Exception {
		return null;
	}
	/**
	 * key;物料编码 val:物料相关信息(map)
	 * @param materialList
	 * @return
	 */
	private Map<String,Object> changeMaterialToMap(List<Map<String,Object>> materialList){
		Map<String,Object> dataMap = new HashMap<>();
		for (Map<String,Object> data : materialList){
			String FNUMBER = VtuzxUtil.getString(data,"FNUMBER");
			String unitNo = VtuzxUtil.getString(data,"unitNo");//单位编码
			Map<String,Object> materialMap = new HashMap<>();
			materialMap.put("FNUMBER",FNUMBER);
			materialMap.put("unitNo",unitNo);
			dataMap.put(FNUMBER,materialMap);
		}
		return dataMap;
	}

}